package com.quectel.business.common.sms;

import cn.hutool.core.util.PhoneUtil;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.profile.DefaultProfile;
import com.quectel.business.common.thirdconfig.ThirdPlatformConfigBusiness;
import com.quectel.constant.global.SMSConstants;
import com.quectel.constant.global.SystemConstants;
import com.quectel.core.module.thirdconfig.dto.item.Sms;
import com.quectel.sys.module.sys.dto.mongo.SmsSendDto;
import com.quectel.sys.module.sys.service.MsgService;
import com.quectel.util.common.JacksonUtils;
import com.quectel.util.http.RequestUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 短信发送
 *
 * @author: caolu
 * @email: louis.cao@quectel.com
 * @date: 2022-05-09 13:27:00
 */
@Component
@Slf4j
public class SmsBusiness {
    @DubboReference
    private MsgService msgService;

    @Autowired
    private ThirdPlatformConfigBusiness thirdPlatformConfigBusiness;

    /**
     * 发送验证码
     *
     * @param tenantId 租户id
     * @param mobile   手机号
     * @param verCode  验证码
     */
    public boolean sendVerCode(Long tenantId, String mobile, String verCode, SMSConstants.VerCodeType verCodeType) {

        if (!PhoneUtil.isMobile(mobile)) {
            return false;
        }

        Sms smsConfig = thirdPlatformConfigBusiness.getSmsConfig(tenantId);
        if (smsConfig == null) {
            return false;
        }

        if (Boolean.TRUE.equals(smsConfig.getMockEnable())) {
            //开启模拟默认为true
            return true;
        }


        DefaultProfile profile = DefaultProfile.getProfile("cn-beijing", smsConfig.getAccessKeyId(), smsConfig.getAccessKeySecret());
        /** use STS Token
         DefaultProfile profile = DefaultProfile.getProfile(
         "<your-region-id>",           // The region ID
         "<your-access-key-id>",       // The AccessKey ID of the RAM account
         "<your-access-key-secret>",   // The AccessKey Secret of the RAM account
         "<your-sts-token>");          // STS Token
         **/
        IAcsClient client = new DefaultAcsClient(profile);

        SendSmsRequest request = new SendSmsRequest();
        request.setPhoneNumbers(mobile);//接收短信的手机号码
        request.setSignName(smsConfig.getSignName());//短信签名名称
        request.setTemplateCode(smsConfig.getVerCodeTemplate());//短信模板CODE

        Map<String, Object> params = new HashMap<>();
        params.put("code", verCode);
        request.setTemplateParam(JacksonUtils.toJsonString(params));//短信模板变量对应的实际值

        try {
            SendSmsResponse response = client.getAcsResponse(request);
            boolean sendSuccess = "OK".equals(response.getCode());
            saveLog(tenantId, mobile, "短信验证码", verCode, "发送类型:" + verCodeType.toString(), sendSuccess);
            return sendSuccess;
        } catch (Exception e) {
            log.error("短信发送失败", e);
        }
        return false;
    }

    /**
     * 发送普通信息
     *
     * @param tenantId 租户id
     * @param mobile   手机号
     * @param title    标题
     * @param content  内容
     */
    public boolean sendCommonMsg(Long tenantId, String mobile, String title, String content) {
        if (!PhoneUtil.isMobile(mobile)) {
            return false;
        }

        Sms smsConfig = thirdPlatformConfigBusiness.getSmsConfig(tenantId);
        if (smsConfig == null) {
            return false;
        }

        if (Boolean.TRUE.equals(smsConfig.getMockEnable())) {
            //开启模拟默认为true
            return true;
        }


        DefaultProfile profile = DefaultProfile.getProfile("cn-beijing", smsConfig.getAccessKeyId(), smsConfig.getAccessKeySecret());
        /** use STS Token
         DefaultProfile profile = DefaultProfile.getProfile(
         "<your-region-id>",           // The region ID
         "<your-access-key-id>",       // The AccessKey ID of the RAM account
         "<your-access-key-secret>",   // The AccessKey Secret of the RAM account
         "<your-sts-token>");          // STS Token
         **/
        IAcsClient client = new DefaultAcsClient(profile);

        SendSmsRequest request = new SendSmsRequest();
        request.setPhoneNumbers(mobile);//接收短信的手机号码
        request.setSignName(smsConfig.getSignName());//短信签名名称
        request.setTemplateCode(smsConfig.getCommonTemplate());//短信模板CODE

        Map<String, Object> params = new HashMap<>();
        params.put("title", title);
        params.put("content", content);
        request.setTemplateParam(JacksonUtils.toJsonString(params));//短信模板变量对应的实际值

        try {
            SendSmsResponse response = client.getAcsResponse(request);
            boolean sendSuccess = "OK".equals(response.getCode());
            saveLog(tenantId, mobile, title, content, null, sendSuccess);
            return sendSuccess;
        } catch (Exception e) {
            log.error("短信发送失败", e);
        }
        return false;
    }

    /**
     * 保存日志
     *
     * @param tenantId
     * @param mobile
     * @param title
     * @param content
     * @param sendSuccess
     */
    private void saveLog(Long tenantId, String mobile, String title, String content, String remark, boolean sendSuccess) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        SmsSendDto smsSendDto = new SmsSendDto();
        smsSendDto.setTenantId(tenantId);
        smsSendDto.setIp(RequestUtils.getRealIp(request));
        smsSendDto.setMobile(mobile);
        smsSendDto.setTitle(title);
        smsSendDto.setContent(content);
        smsSendDto.setCreateTime(new Date());
        smsSendDto.setStatus(sendSuccess ? SystemConstants.YES : SystemConstants.NO);
        msgService.saveSmsRecord(smsSendDto);
    }

}
